package com.weixin.program.utils;

import com.alibaba.fastjson.JSON;
import com.weixin.program.ro.AccessToken;
import com.weixin.program.ro.UserData;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年02⽉26⽇<br/>
 * @version：v1.0.0<br>
 */
@Slf4j
public class WeixinUtil {

    /**
     * 校验签名
     *
     * @param params
     * @return
     */
    public static String getSHA1(String... params) {
        try {
            String[] array = (String[]) params.clone();
            StringBuilder sb = new StringBuilder();

            Arrays.sort(array);
            for (String anArray : array) {
                if (anArray != null) {
                    sb.append(anArray);
                }
            }
            String str = sb.toString();

            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuilder hexstr = new StringBuilder();
            for (byte aDigest : digest) {
                String shaHex = Integer.toHexString(aDigest & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析接收参数
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static Map parseXml(HttpServletRequest request) throws Exception {
        // 将解析结果存储在HashMap中
        Map map = new HashMap();

        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        /*
         * 读取request的body内容 此方法会导致流读取问题 Premature end of file. Nested exception:
         * Premature end of file String requestBody =
         * inputStream2String(inputStream); System.out.println(requestBody);
         */
        // 读取输入流
        SAXReader reader = new SAXReader();
        reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        // 释放资源
        inputStream.close();
        inputStream = null;
        return map;
    }

    /**
     * 获取token
     *
     * @param appId
     * @param appSecret
     * @return
     * @throws IOException
     */
    public static String getToken(String appId, String appSecret) throws IOException {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String response = HttpClientProxy.get(requestUrl, "");
        AccessToken accessToken = JSON.parseObject(response, AccessToken.class);
        return accessToken.getAccessToken();
    }

    public static UserData getUserData(String userId, String token) throws IOException {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + userId + "&lang=zh_CN";
        String response = HttpClientProxy.get(requestUrl, "");
        UserData userData = JSON.parseObject(response, UserData.class);
        return userData;
    }
}
